<?php

namespace App\Helper;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\Config;
use App\ATrait\Single;
use Exception;
use Illuminate\Support\Facades\Log;

class AliYunSmsNotice
{

    use Single;

    protected \App\Helper\Config $configRe;


    public function __construct()
    {
        $this->configRe = \App\Helper\Config::getInstance();
    }


    /**
     * 发送短信通知---给管理员
     *
     * @param $event
     * @return array
     */
    public function SendCode($event): array
    {

        $sign = $this->configRe->Get('aliyun_business_notice_sms_sign');
        $template = $this->configRe->Get('aliyun_business_notice_sms_template');
        $phoneArr = json_decode($this->configRe->Get('business_notice_phone')) ?? [];
        $client = self::createClient();
        $TemplateParam = [
            'platform' => '开发者平台',
            'event' => $event,
        ];

        Log::info(111, $TemplateParam);

        try {
            foreach ($phoneArr as $phone) {
                $sendSmsRequest = new SendSmsRequest([
                    'phoneNumbers' => $phone,
                    'signName' => $sign,
                    'templateCode' => $template,
                    'templateParam' => json_encode($TemplateParam)
                ]);
                $runtime = new RuntimeOptions([]);
                $client->sendSmsWithOptions($sendSmsRequest, $runtime);
            }
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            return ['state' => false, 'data' => $error->message];
        }

        return ['state' => true];
    }


    /**
     * 使用AK&SK初始化账号Client
     *
     * @return Dysmsapi Client
     */
    public function CreateClient(): Dysmsapi
    {
        $config = new Config([
            'accessKeyId' => $this->configRe->Get('aliyun_sms_access_key_id'),
            'accessKeySecret' => $this->configRe->Get('aliyun_sms_access_key_secret'),
        ]);
        $config->endpoint = $this->configRe->Get('aliyun_sms_endpoint');

        return new Dysmsapi($config);
    }

}
